package memorphic.slide
{
	import mx.core.UIComponent;
	import mx.effects.easing.Elastic;
	import mx.states.IOverride;
	
	
	/**
	 * TODO: Relocate to memorphic.states.* package
	 */
	
	[DefaultProperty("overrides")]
	public class StateOverlay implements IOverride
	{
		
		private var initedOverrides:Boolean = false;
		private var initedElseOverrides:Boolean = false;
		
		
		private var __overrides:Array = [];
		private var __otherwise:Array = [];
		
		private var __condition:Boolean = false;
		
		private var isApplied:Boolean = false;
		
		
		private var __parent:UIComponent;
		
		
		public function StateOverlay()
		{
		}
		
		
		[ArrayElementType("mx.states.IOverride")]
		public function get overrides():Array
		{
			return __overrides;
		}
		public function set overrides(overrides:Array):void
		{
			__overrides = overrides || [];
			initedElseOverrides = false;
			initialize();
		}
		
		[ArrayElementType("mx.states.IOverride")]
		public function get otherwise():Array
		{
			return __otherwise;
		}
		public function set otherwise(overrides:Array):void
		{
			__otherwise = overrides || [];
			initedElseOverrides = false;
			initialize();
		}
		
		
		public function get condition():Boolean
		{
			return __condition;
		}
		public function set condition(bool:Boolean):void
		{
			var oldCondition:Boolean = __condition;
			__condition = bool;
			if(oldCondition != bool){
				conditionChanged();
			}
		}
		
		
		private function conditionChanged():void
		{
			if(isApplied){
				if(condition){
					removeChildOverrides(otherwise);
					applyChildOverrides(overrides);
				}else{
					removeChildOverrides(overrides);
					applyChildOverrides(otherwise);
				}
			}
		}
		
		
		private function applyChildOverrides(overrides:Array):void
		{
			var n:int = overrides.length;
			for(var i:int=0; i<n; i++){
				IOverride(overrides[i]).apply(__parent);
			}
		}
		
		private function removeChildOverrides(overrides:Array):void
		{
			var n:int = overrides.length;
			for(var i:int=0; i<n; i++){
				IOverride(overrides[i]).remove(__parent);
			}
		}
		
		
		private function initOverrides(overrides:Array):void
		{				
			var n:int = overrides.length;
			for(var i:int=0; i<n; i++){
				IOverride(overrides[i]).initialize();
			}
		}
		
		public function initialize():void
		{
			if(!initedOverrides){
				initOverrides(overrides);
				initedOverrides = true;	
			} 
			if(!initedElseOverrides){
				initOverrides(otherwise);
				initedElseOverrides = true;	
			} 
		}
		
		
		
		
		public function apply(parent:UIComponent):void
		{
			__parent = parent;
			if(condition){
				applyChildOverrides(overrides);
			}else{
				applyChildOverrides(otherwise);
			}
			isApplied = true;
		}
		
		public function remove(parent:UIComponent):void
		{
			if(condition){
				removeChildOverrides(overrides);
			}else{
				removeChildOverrides(otherwise);
			}
			isApplied = false;
			__parent = null;
		}

	}
}